package org.jflame.web.servlet;

import org.jflame.commons.codec.Transcoder;
import org.jflame.commons.config.ConfigHolder;
import org.jflame.commons.file.MimeTypes;
import org.jflame.commons.model.CallResult;
import org.jflame.commons.util.ArrayHelper;
import org.jflame.commons.util.CollectionHelper;
import org.jflame.commons.util.StringHelper;
import org.jflame.web.ServletParamConfig;
import org.jflame.web.WebFileProperties;
import org.jflame.web.WebFileProperties.UploadProp;
import org.jflame.web.WebFileService;
import org.jflame.web.WebUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

/**
 * 文件上传或下载servlet
 */
@SuppressWarnings("serial")
public class FileServlet extends HttpServlet {

    private boolean preview;
    private WebFileService service;
    private WebFileProperties defaultCfg = new WebFileProperties();

    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletParamConfig servletParam = new ServletParamConfig(config);

        if (!servletParam.bindBean(defaultCfg, "upload.") && !servletParam.bindBean(defaultCfg, "download.")) {
            if (ConfigHolder.getConfig() != null) {
                ConfigHolder.getConfig()
                        .bindBean(defaultCfg, WebFileProperties.PREFIX);
            }
        }
        if (defaultCfg.getDownload()
                .getAllowTypes() == null) {
            defaultCfg.getDownload()
                    .setAllowTypes(ArrayHelper.unionAll(MimeTypes.WEB_IMAGE_EXTENSIONS, MimeTypes.DOC_EXTENSIONS));
        }
        // 文档或图片类型按mimeType输出,而不是弹出下载框
        preview = servletParam.getBoolean("enable-preview", true);
        if (preview) {
            defaultCfg.getDownload()
                    .setKeepContentType(preview);
        }
        if (defaultCfg.getUpload()
                .getAllowTypes() == null) {
            defaultCfg.getUpload()
                    .setAllowTypes(ArrayHelper.unionAll(MimeTypes.WEB_IMAGE_EXTENSIONS, MimeTypes.DOC_EXTENSIONS));
        }

    }

    /**
     * 文件下载
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        // 处理生成上传预签名操作
        if ("presign".equals(action)) {
            String dir = request.getParameter("dir");
            String method = request.getParameter("method");
            String fileKey = request.getParameter("fileExt");
            CallResult<?> result;
            UploadProp prop;
            if (StringHelper.isNotEmpty(dir)) {
                prop = new UploadProp();
                prop.setDir(dir);
                prop.setAllowTypes(defaultCfg.getUpload()
                        .getAllowTypes());
                prop.setPresginExpireTime(defaultCfg.getUpload()
                        .getPresginExpireTime());
                prop.setMaxFileSize(defaultCfg.getUpload()
                        .getMaxFileSize());
            } else {
                prop = defaultCfg.getUpload();
            }
            // 生成post方式上传的参数,
            if ("post".equals(method)) {
                result = service.generatePostObjectParams(fileKey, prop);
            } else {
                // put上传的签名url
                result = service.generatePresignPutUrl(fileKey, prop);
            }

            WebUtils.outJson(response, result);
        } else {
            // 处理下载操作
            String downFile = request.getParameter("file");
            if (StringHelper.isNotEmpty(downFile)) {
                downFile = Transcoder.urlDecode(downFile);
            } else {
                downFile = request.getPathInfo();
            }
            if (StringHelper.isEmpty(downFile)) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            service.download(downFile, defaultCfg.getDownload(), response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        if (CollectionHelper.isEmpty(parts)) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "请选择上传文件");
            return;
        }
        Map<String,String> uploadResult = service.upload(defaultCfg.getUpload(), req);
        WebUtils.outJson(resp, uploadResult);
    }

    public void setService(WebFileService service) {
        this.service = service;
    }

    public void destroy() {
        super.destroy();
    }
}
